package com.itheima.service.impl;

import com.itheima.domain.Category;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {
    private final CategoryMapper categoryMapper;

    @Override
    public List<Category> getCategory() {
        List<Category> allCategoryList = categoryMapper.getAll();

        List<Category> parents = allCategoryList.stream().filter(category -> category.getParentId()==0).toList();
        List<Category> allChildren = allCategoryList.stream().filter(category -> category.getParentId()>0).toList();

        parents.forEach( p -> {
            setAllChildren(p,allChildren);
        });

        return parents;
    }

    public static void setAllChildren(Category parent,List<Category> allChildren){
        List<Category> currentChildren = allChildren.stream().filter(category -> Objects.equals(category.getParentId(), parent.getId())).toList();

        currentChildren.forEach(category -> {
            setAllChildren(category,allChildren);
        });

        parent.setChildren(currentChildren);
    }
}
